package com.bjc.netty.c11;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @program: nettypro
 * @description: 黏包 半包解决 LTC解码器
 * @author: bjc
 * @create: 2021-09-25 19:52
 */
public class TestLengthFieldDecoder {

    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024,0,4,1,4),
                new LoggingHandler(LogLevel.DEBUG)
        );

        //4个字节的内容长度  实际内容
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        send(buffer,"Hello,world");
        send(buffer,"Hi!");

        channel.writeInbound(buffer);
    }

    private static void send(ByteBuf byteBuf, String content) {
        //实际内容
        byte[] bytes = content.getBytes();
        //实际内容长度
        int length = bytes.length;
        byteBuf.writeInt(length);
        byteBuf.writeByte(1);
        byteBuf.writeBytes(bytes);
    }
}
